/*
 * This source code is part of TWaver 4.0
 *
 * Serva Software PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Copyright 2002 - 2011 Serva Software. All rights reserved.
 */

package demo.editor.pipe.element;

import java.awt.Rectangle;
import twaver.TWaverConst;
import twaver.TWaverUtil;
import demo.editor.pipe.Const;
import demo.editor.pipe.ui.RoundPipeUI;

public class RoundPipe extends AbstractPipe {
	
	private int holeCount = 0; 
    private boolean centerHole = true;
    
	public RoundPipe() {
    	super();
    	init();
    }

    public RoundPipe(Object id) {
        super(id);
        init();
    }
    
    private void init(){
    	this.setName("RoundPipe");
    	this.setSize(160, 160);
		this.putCustomDrawShapeFactory(TWaverConst.SHAPE_ROUND);
		this.putCustomDrawGradientFactory(TWaverConst.GRADIENT_RADIAL_NW);
		this.setIcon("/demo/editor/pipe/element/PipeHole.png");
    }
    
    public String getUIClassID() {
        return RoundPipeUI.class.getName();
    }

	public int getHoleCount() {
		return holeCount;
	}

	public void setHoleCount(int holeCount) {
		Object oldValue = TWaverUtil.valueOf(this.holeCount);
		this.holeCount = holeCount;
		this.firePropertyChange(Const.PROPERTYNAME_ROUNDPIPE_HOLECOUNT, oldValue, TWaverUtil.valueOf(this.holeCount));
		if(this.holeCount > 0){
			this.setIcon("/demo/editor/pipe/element/RoundPipe.png");
		}else{
			this.setIcon("/demo/editor/pipe/element/PipeHole.png");
		}
	}

	public boolean isCenterHole() {
		return centerHole;
	}

	public void setCenterHole(boolean centerHole) {
		Object oldValue = Boolean.valueOf(this.centerHole);
		this.centerHole = centerHole;
		this.firePropertyChange(Const.PROPERTYNAME_ROUNDPIPE_CENTERHOLE, oldValue, Boolean.valueOf(this.centerHole));
	}

	public Rectangle getPipeHoleBoundsByHoleIndex(int holeIndex){
		if(holeIndex < 0 || holeIndex >= this.holeCount){
			return null;
		}
		double R = Math.min(this.getWidth(), this.getHeight()) / 2.0;
		double cx = this.getLocation().x + this.getWidth() / 2.0;
		double cy = this.getLocation().y + this.getHeight() / 2.0;
		double count = this.centerHole ? this.holeCount - 1 : this.holeCount;
		double angle = Math.toRadians(180 / count);
		double r = R * Math.sin(angle) / (1 + Math.sin(angle));
		double x = (R - r) * Math.sin(angle * 2 * holeIndex);
		double y = (R - r) * Math.cos(angle * 2 * holeIndex);
		if(this.centerHole && holeIndex == this.holeCount - 1){
			r = R - 2 * r;
			return new Rectangle((int)(cx-r), (int)(cy-r), (int)(2*r), (int)(2*r));
		}
		else{
			return new Rectangle((int)(cx+x-r), (int)(cy+y-r), (int)(2*r), (int)(2*r));
		}
	}
}